package com.asen.libcommon.widget.image

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView


/**
 * @date   : 2020/12/11
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : 宽度填满，高度自适应图片控件
 *
 *  <com.asen.libcommon.widget.image.FlexHeightImageView
 *     android:id="@+id/image"
 *     android:layout_width="fill_parent"
 *     android:layout_height="wrap_content"
 *     android:src="@drawable/test"
 *     android:background="#FF0"
 *   />
 */

class FlexHeightImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val d = drawable
        if (d != null) {
            // ceil not round - avoid thin vertical gaps along the left/right edges
            val width = MeasureSpec.getSize(widthMeasureSpec)
            //高度根据使得图片的宽度充满屏幕计算而得
            val height =
                Math.ceil((width.toFloat() * d.intrinsicHeight.toFloat() / d.intrinsicWidth).toDouble())
                    .toInt()
            setMeasuredDimension(width, height)
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        }
    }

}